// pages/movies/movies.js
var util = require('../utils/util.js');
var app = getApp();

Page({

  data: {
    inTheaters: {},
    comingSoon: {},
    top250: {},
    searchResult: {},
    containerShow: true,
    searchPanelShow: false
  },

  // RESTFul API JSON
  // SOAP XML
  //粒度 不是 力度

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (event) {
    //正在热映
    var inTheatersUrl = app.globalData.doubanBase + '/v2/movie/in_theaters' + '?start=0&count=3';
    //即将上映
    var comingSoonUrl = app.globalData.doubanBase + '/v2/movie/coming_soon' + '?start=0&count=3';
    //Top250
    var top250Url = app.globalData.doubanBase + '/v2/movie/top250' + '?start=0&count=3';

    this.getMovieListData(inTheatersUrl,"inTheaters","正在热映");
    this.getMovieListData(comingSoonUrl,"comingSoon","即将上映");
    this.getMovieListData(top250Url,"top250","豆瓣Top250");
  },

  // 更多 绑定事件
  onMoreTap:function(event) {
    var category = event.currentTarget.dataset.category;
    wx.navigateTo({
      url: 'more-movie/more-movie?category=' + category,
    })
  },

  //电影详情点击事件
  onMovieTap: function(event) {
    var movieId = event.currentTarget.dataset.movieid;
    wx.navigateTo({
      url: 'movie-detail/movie-detail?id=' + movieId
    })
  },

  getMovieListData: function (url,settedKey,categoryTitle) {
    var that = this;
    wx.request({
      url: url,
      method: 'GET',
      header: { "Content-Type": "json" },
      success: function (res) {
        that.processDoubanData(res.data,settedKey,categoryTitle);
      },
      fail: function (error) {
        // fail
        console.log(error)
      }
    })
  },

  //搜索图片取消事件
  onCancelImgTap: function() {
    this.setData({
      containerShow: true,
      searchPanelShow: false
    })
  },

  //搜索框绑定事件
  onBindFocus: function(event) {
    this.setData({
      containerShow: false,
      searchPanelShow: true,
      searchResult: {}
    })
  },

  onBindBlur: function(event) {
    //获取搜索框文本值
    var text = event.detail.value;
    var searchUrl = "http://t.yushu.im" + "/v2/movie/search?q=" + text;
    this.getMovieListData(searchUrl,"searchResult","");
  },

  processDoubanData: function(moviesDouban,settedKey,categoryTitle) {
    var movies = [];
    for (var idx in moviesDouban.subjects) {
      var subject = moviesDouban.subjects[idx];
      var title = subject.title;
      if (title.length >= 6) {
        title = title.substring(0, 6) + "...";
      }

      var temp = {
        stars: util.convertToStarsArray(subject.rating.stars),
        title: title,
        average: subject.rating.average,
        coverageUrl: subject.images.large,
        movieId: subject.id
      };
      movies.push(temp);
    } 
    var readyData = {};
    readyData[settedKey] = {
      categoryTitle: categoryTitle,
      movies : movies
    }
    this.setData(readyData)
  }
})